<?php
namespace app\shop\model;
use app\BaseModel;
use think\facade\Db;



class IndexSellingProfit extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_selling_profit';


    /**
     * User: chenniang
     * Date: 2019-10-11 15:30
     * @param $value
     * @param $data
     * @return void
     * descption:待入帐
     */
    public function getWaitingAttr($value,$data){
        $selling_water = new IndexSellingWater();
        $list = $selling_water->where(['user_id'=>$data['user_id'],'waiting'=>1,'status'=>1])->select()->toArray();
        $cash = 0;
        if(!empty($list)){
            foreach ($list as $v){
                $cash+=$v['extract_money_text'];
            }
        }
        return round($cash,2);
    }
    /**
     * @param $dis
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取分销信息
     */
    public function profitInfo($dis){
        $data = $this->where($dis)->find();
        return !empty($data)?$data->toArray():$data;
    }


    /**
     * @param $data
     * @return int|string
     * 添加分销
     */
    public function profitAdd($data){
        $data['create_time'] = time();
        $data['update_time'] = time();
        $res = $this->insert($data);
        return $res;
    }
    /**
     * @param $data
     * @return int|string
     * 编辑分销
     */
    public function profitUpdate($dis,$data){
        $data['update_time'] = time();
        $res = $this->where($dis)->update($data);
        return $res;
    }


    /**
     * @param $dis
     * @param $price
     * @功能说明:增减佣金
     * @author chenniang
     * @DataTime: 2020-04-22 09:39
     */
    public function incOrDecCash($water){

        $dis['uniacid'] = $water['uniacid'];

        $dis['user_id'] = $water['user_id'];
        //用户的佣金信息）
        $info = $this->profitInfo($dis);
        //没有就生成
        if(empty($info)){

            $this->profitAdd($dis);
            //用户的佣金信息）
            $info = $this->profitInfo($dis);
        }

        if($water['selling_type']==0){

            $today_profit = ($water['price'] * $water['extract'] / 100);

        }else{

            $today_profit = $water['extract_cash'];
        }
        //结算
        if($water['waiting']==2){

            $raw = [

                'profit'       => Db::raw("profit+$today_profit"),

                'total_profit' => Db::raw("total_profit+$today_profit")

            ];

            if(!in_array($water['selling_type'],[1,2,3])){

                $raw['waiting'] = $info['waiting']-$today_profit>0?$info['waiting']-$today_profit:0;
            }

        }else{
        //待入帐
            $raw =[

                'waiting' => Db::raw("waiting+$today_profit"),
            ];

        }
        //增加佣金
        $res = $this->where($dis)->update($raw);

        return $res;

    }


}